<template>
  <div class="add-task-container">

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="add-task-wrapper">
        <h2 class="page-title">添加课程任务项</h2>
        
        <!-- 添加任务项表单 -->
        <el-form ref="taskForm" :model="taskForm" :rules="taskRules" label-width="100px" class="task-form">
          <el-form-item label="课程名称" prop="courseId">
            <el-select v-model="taskForm.courseId" placeholder="请选择课程">
              <el-option
                v-for="course in courses"
                :key="course.id"
                :label="course.title"
                :value="course.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="任务项标题" prop="title">
            <el-input v-model="taskForm.title" placeholder="请输入任务项标题"></el-input>
          </el-form-item>
          <el-form-item label="任务项内容" prop="body">
            <el-input
              v-model="taskForm.body"
              type="textarea"
              placeholder="请输入任务项详细内容"
              :rows="6"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAddTask" :loading="loading">添加任务项</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <p>© 2025 课程学习网站 | 数字化成长空间</p>
    </footer>
  </div>
</template>

<script>
import { subitemAPI, courseAPI } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'AddTaskView',
  data() {
    return {
      activeIndex: 'add-task',
      taskForm: {
        courseId: '',
        title: '',
        body: ''
      },
      taskRules: {
        courseId: [
          { required: true, message: '请选择课程', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入任务项标题', trigger: 'blur' },
          { min: 2, max: 50, message: '任务项标题长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        body: [
          { required: true, message: '请输入任务项内容', trigger: 'blur' },
          { min: 5, max: 2000, message: '任务项内容长度在 5 到 2000 个字符', trigger: 'blur' }
        ]
      },
      courses: [],
      loading: false
    }
  },
  computed: {
    userInfo() {
      try {
        const userInfoStr = localStorage.getItem('userInfo')
        if (userInfoStr) {
          // 尝试直接解析
          try {
            return JSON.parse(userInfoStr)
          } catch (e) {
            // 如果解析失败，尝试解码可能被URL编码的字符串
            try {
              const decodedStr = decodeURIComponent(userInfoStr)
              return JSON.parse(decodedStr)
            } catch (decodeError) {
              console.error('解析用户信息失败:', e, decodeError)
              return null
            }
          }
        }
        return null
      } catch (error) {
        console.error('获取用户信息出错:', error)
        return null
      }
    }
  },
  async mounted() {
    // 检查URL中是否有课程ID参数
    if (this.$route.query.courseId) {
      this.taskForm.courseId = this.$route.query.courseId
    }
    await this.loadCourses()
  },
  methods: {
    async loadCourses() {
      try {
        // 获取当前用户的所有课程
        const coursesResponse = await courseAPI.getAllCourses()
        
        // 确保courses是数组，处理各种可能的响应格式
        const courses = Array.isArray(coursesResponse) ? coursesResponse : 
                          (coursesResponse && typeof coursesResponse === 'object' && 'data' in coursesResponse) ? coursesResponse.data : []
        
        this.courses = courses
      } catch (error) {
        console.error('加载课程列表错误:', error)
        ElMessage.error('加载课程列表失败，请稍后重试')
        this.courses = []
      }
    },
    async handleAddTask() {
      try {
        this.$refs.taskForm.validate(async (valid) => {
          if (valid) {
            this.loading = true
            
            // 检查用户是否登录
            if (!this.userInfo) {
              ElMessage.error('请先登录')
              this.loading = false
              return
            }
            
            // 确保courseId有效
            if (!this.taskForm.courseId) {
              ElMessage.error('请选择课程')
              this.loading = false
              return
            }
            
            console.log('即将添加任务项到课程:', this.taskForm.courseId)
            
            // 准备任务项数据
            const taskData = {
              ...this.taskForm,
              courseId: this.taskForm.courseId,
              userId: this.userInfo.id,
              authorName: this.userInfo.username || '用户'
            }
            
            try {
              // 添加新任务项
              const response = await subitemAPI.addCourseSubitem(taskData)
              
              console.log('添加任务项响应:', response)
              
              // 响应处理逻辑
              if (response && (response.errno === 0 || response.success === true)) {
                ElMessage.success('任务项添加成功')
                
                // 重置表单
                this.resetForm()
                
                // 使用Vue Router跳转到课程详情页
                const courseId = this.taskForm.courseId
                console.log('准备跳转到课程详情页:', courseId)
                
                try {
                  // 使用$router.push进行跳转，这是Vue应用中推荐的路由跳转方式
                  this.$router.push(`/course/${courseId}`)
                } catch (error) {
                  console.error('路由跳转失败:', error)
                  ElMessage.error('跳转失败，请手动返回课程详情页')
                }
              } else {
                console.warn('添加任务项响应不符合预期:', response)
                ElMessage.error('添加任务项失败，请稍后重试')
              }
            } catch (error) {
              console.error('添加任务项错误:', error)
              let errorMessage = '添加任务项失败，请稍后重试'
              if (error.response?.data?.message) {
                errorMessage = error.response.data.message
              } else if (error.message) {
                errorMessage = error.message
              }
              ElMessage.error(errorMessage)
            } finally {
              this.loading = false
            }
          }
        })
      } catch (error) {
        console.error('表单验证或提交过程出错:', error)
        ElMessage.error('添加任务项过程中出现错误，请稍后重试')
        this.loading = false
      }
    },
    resetForm() {
      this.taskForm = {
        courseId: '',
        title: '',
        body: ''
      }
      if (this.$refs.taskForm) {
        this.$refs.taskForm.resetFields()
      }
    },
    handleCancel() {
      this.resetForm()
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
.add-task-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}



/* 主内容区样式 */
.main-content {
  flex: 1;
  max-width: 1200px;
  width: 100%;
  margin: 20px auto;
  padding: 0 20px;
}

/* 添加任务项包装 */
.add-task-wrapper {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

/* 页面标题 */
.page-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 30px;
  text-align: center;
}

/* 任务项表单 */
.task-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

/* 页脚 */
.footer {
  background-color: #fff;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #e6e6e6;
  margin-top: auto;
}

.footer p {
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-task-wrapper {
    padding: 20px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .task-form {
    max-width: 100%;
    padding: 15px;
  }
}
</style>